<!-- 新增角色对话框 -->
<template>
    <el-dialog v-model="dialogFormVisible" title="权限分配" width="600">
        <div class="tree">
            <el-tree ref="treeRef" style="max-width: 600px" :data="data" show-checkbox default-expand-all node-key="id"
                highlight-current :props="defaultProps" :default-checked-keys="checks" />
        </div>
        <template #footer>
            <div class=" dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue'
import { reqGetRoleMenu, reqGetMenu, reqSaveMenu } from '../../../api/user/index'
import { GetAdminRoleMenuResponseData, GetMenuResponseData, MenuList } from '../../../api/user/type';
import $bus from '../../../bus'
let dialogFormVisible = ref<Boolean>(false)
// let checks: Array<number> = []
let checks = ref<number[]>([])
let roleId = ref<number>(0)
const defaultProps = {
    children: 'childMenuList',
    label: 'menuName',
}
let treeRef = ref()
const data = reactive<MenuList>([])


onMounted(() => {
    $bus.on('Dialog', (obj: any) => {
        dialogFormVisible.value = obj.isShow
        roleId.value = obj.id
        getMenu()
        nextTick(() => {
            getCurrentRoleMenu(obj.id)
        })
    })
})
// 获取当前角色的菜单列表
const getCurrentRoleMenu = async (roleId: number) => {
    let result: GetAdminRoleMenuResponseData = await reqGetRoleMenu(roleId)
    if (result.code == 20000) {
        checks.value = result.data

    }
}
// 获取菜单
const getMenu = async () => {
    let result: GetMenuResponseData = await reqGetMenu()
    if (result.code == 20000) {
        Object.assign(data, result.data)

    }
}
const submit = async () => {
    let data = treeRef.value.getCheckedKeys()
    let result: any = await reqSaveMenu(data, roleId.value)
    if (result.code == 20000) {
        ElMessage({
            type: 'success',
            message: '权限分配成功'
        })
    } else {
        ElMessage({
            type: 'error',
            message: '权限分配失败'
        })
    }
    dialogFormVisible.value = false
}
</script>

<style lang="scss" scoped>
.tree {
    padding: 10px 50px
}
</style>